<template>
  <div class="edit-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑分类' : '新增分类' }}</span>
          <el-button @click="router.back()">返回</el-button>
        </div>
      </template>

      <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="120px"
          style="max-width: 600px;"
      >
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>

        <el-form-item label="父级分类" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择父级分类" style="width: 100%">
            <el-option label="根分类" :value="null" />
            <el-option
                v-for="category in categoryTree"
                :key="category.categoryId"
                :label="category.categoryName"
                :value="category.categoryId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="分类描述" prop="description">
          <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入分类描述"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
          <el-button @click="router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { herbCategoryApi } from '@/api/admin'

const route = useRoute()
const router = useRouter()
const formRef = ref()
const loading = ref(false)
const categoryTree = ref([])

const isEdit = computed(() => route.params.id !== undefined)

const form = reactive({
  categoryId: null,
  categoryName: '',
  parentId: null,
  description: ''
})

const rules = {
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ]
}

const loadCategoryTree = async () => {
  try {
    const res = await herbCategoryApi.getTree()
    categoryTree.value = res.data || []
  } catch (error) {
    ElMessage.error('加载分类树失败')
  }
}

const loadCategoryDetail = async (id) => {
  try {
    const res = await herbCategoryApi.getById(id)
    Object.assign(form, res.data)
  } catch (error) {
    ElMessage.error('加载分类详情失败')
    router.back()
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    loading.value = true
    try {
      if (isEdit.value) {
        await herbCategoryApi.update(form)
        ElMessage.success('更新成功')
      } else {
        await herbCategoryApi.add(form)
        ElMessage.success('创建成功')
      }
      router.push('/admin/herb-category')
    } catch (error) {
      ElMessage.error('操作失败')
    } finally {
      loading.value = false
    }
  })
}

onMounted(() => {
  loadCategoryTree()
  if (isEdit.value) {
    loadCategoryDetail(route.params.id)
  }
})
</script>
